<template>
  <div class="min-h-screen bg-gradient-to-br from-green-50 to-blue-50 py-8">
    <div class="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8">
      <div class="text-center mb-8">
        <h1 class="text-3xl font-bold text-gray-900 mb-2">在线剪贴板</h1>
        <p class="text-gray-600">粘贴内容，设置过期时间（最长 7 天），并使用密钥保存与读取。密钥即 Redis 的 key，内容作为 value 存储。</p>
      </div>

      <div class="bg-white p-6 rounded-lg shadow">
        <label class="block text-sm font-medium text-gray-700 mb-2">密钥 (Key)</label>
        <input v-model="key" type="text" class="w-full border rounded px-3 py-2 mb-4" placeholder="输入用于存取的密钥（必填）" />

        <label class="block text-sm font-medium text-gray-700 mb-2">内容 (Value)</label>
        <textarea v-model="value" rows="8" class="w-full border rounded px-3 py-2 mb-4" placeholder="粘贴或输入要保存的文本（必填）"></textarea>

        <div class="grid grid-cols-2 gap-4 items-end mb-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">过期时间</label>
            <select v-model.number="expireSeconds" class="w-full border rounded px-3 py-2">
              <option :value="3600">1 小时</option>
              <option :value="6*3600">6 小时</option>
              <option :value="24*3600">1 天（默认）</option>
              <option :value="3*24*3600">3 天</option>
              <option :value="7*24*3600">7 天（最长）</option>
            </select>
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">操作</label>
            <div class="flex space-x-2">
              <button @click="save" class="primary-button px-4 py-2">保存</button>
              <button @click="load" class="border rounded px-4 py-2">读取</button>
              <button @click="generateShareLink" class="border rounded px-4 py-2">生成分享链接</button>
              <button @click="clearLocal" class="text-sm text-gray-500 px-3 py-2">清空输入</button>
            </div>
          </div>
        </div>

        <div v-if="message" class="mt-4 text-sm text-gray-700">{{ message }}</div>

        <div v-if="shareLink" class="mt-4">
          <label class="block text-sm font-medium text-gray-700 mb-2">分享链接</label>
          <div class="flex space-x-2">
            <input :value="shareLink" readonly class="flex-1 border rounded px-3 py-2" />
            <button @click="copyShareLink" class="border rounded px-4 py-2">复制</button>
          </div>
        </div>

        <!-- 读取的内容直接填入输入框供编辑，原本的只读显示已移除 -->
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'

const key = ref('')
const value = ref('')
const expireSeconds = ref(24 * 3600)
const message = ref('')
// avoid TypeScript-style annotation in a non-TS <script setup>
const loadedValue = ref(null)
const route = useRoute()
const shareLink = ref('')

// helper: cap to 7 days
function capExpire(s) {
  const max = 7 * 24 * 3600
  if (!Number.isFinite(s) || s <= 0) return 24 * 3600
  return s > max ? max : Math.floor(s)
}

async function save() {
  message.value = ''
  loadedValue.value = null
  if (!key.value.trim()) {
    message.value = '请填写密钥（Key）。'
    return
  }
  if (!value.value) {
    message.value = '请填写要保存的内容。'
    return
  }

  const expire = capExpire(Number(expireSeconds.value))

  try {
    const res = await fetch('/api/clipboard', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ key: key.value.trim(), value: value.value, expireSeconds: expire })
    })
    const data = await res.json()
    if (!res.ok) {
      message.value = data?.message || '保存失败'
      return
    }
    message.value = `已保存，key=${data.key}，过期 ${data.expireSeconds} 秒` 
  } catch (err) {
    message.value = '保存时发生错误：' + String(err)
  }
}

async function load() {
  message.value = ''
  loadedValue.value = null
  if (!key.value.trim()) {
    message.value = '请填写密钥（Key）以读取。'
    return
  }
  try {
    const url = `/api/clipboard?key=${encodeURIComponent(key.value.trim())}`
    const res = await fetch(url)
    const data = await res.json()
    if (!res.ok) {
      message.value = data?.message || '读取失败'
      return
    }
    // 将读取到的内容直接填入输入框，便于用户编辑
    value.value = data.value || ''
    if (data.expireSeconds) expireSeconds.value = Number(data.expireSeconds)
    message.value = `读取成功并已填入输入框，key=${data.key}`
  } catch (err) {
    message.value = '读取时发生错误：' + String(err)
  }
}

async function generateShareLink() {
  message.value = ''
  shareLink.value = ''
  if (!key.value || !key.value.trim()) {
    message.value = '请先填写或加载一个密钥（Key），然后生成分享链接。'
    return
  }
  try {
    const origin = typeof window !== 'undefined' ? window.location.origin : ''
    const path = route?.path || window.location.pathname || '/text-tools/clipboard'
    const link = `${origin}${path}?key=${encodeURIComponent(key.value.trim())}`
    // 尝试复制到剪贴板
    if (navigator.clipboard && navigator.clipboard.writeText) {
      await navigator.clipboard.writeText(link)
      message.value = '已生成分享链接并复制到剪贴板。'
    } else {
      // fallback: set message and still show the link for manual复制
      message.value = '已生成分享链接（请手动复制）。'
    }
    shareLink.value = link
  } catch (err) {
    message.value = '生成分享链接时发生错误：' + String(err)
  }
}

async function copyShareLink() {
  if (!shareLink.value) return
  try {
    if (navigator.clipboard && navigator.clipboard.writeText) {
      await navigator.clipboard.writeText(shareLink.value)
      message.value = '分享链接已复制到剪贴板。'
    } else {
      // fallback: create a temporary textarea
      const ta = document.createElement('textarea')
      ta.value = shareLink.value
      document.body.appendChild(ta)
      ta.select()
      document.execCommand('copy')
      document.body.removeChild(ta)
      message.value = '分享链接已复制到剪贴板（使用回退方法）。'
    }
  } catch (err) {
    message.value = '复制分享链接失败：' + String(err)
  }
}

function clearLocal() {
  key.value = ''
  value.value = ''
  loadedValue.value = null
  message.value = ''
}

// 如果 URL 带有 ?key=xxx，页面加载时自动读取并填充到输入框
onMounted(async () => {
  try {
    const q = route?.query?.key
    if (!q) return
    const k = Array.isArray(q) ? q[0] : String(q)
    if (!k || !k.trim()) return
    key.value = k.trim()
    // 复用 load 的逻辑但不显示为已读取区
    const url = `/api/clipboard?key=${encodeURIComponent(key.value)}`
    const res = await fetch(url)
    const data = await res.json()
    if (!res.ok) {
      message.value = data?.message || '通过 key 自动读取失败'
      return
    }
    value.value = data.value || ''
    if (data.expireSeconds) expireSeconds.value = Number(data.expireSeconds)
    message.value = `通过 key 自动读取并已填入输入框，key=${data.key}`
  } catch (err) {
    message.value = '自动读取时发生错误：' + String(err)
  }
})

useHead({
  title: '在线剪贴板 - 文本工具',
  meta: [{ name: 'description', content: '在线剪贴板，设置过期时间与密钥，数据存入 Redis' }]
})
</script>

<style scoped>
.primary-button { background: linear-gradient(90deg,#10b981,#06b6d4); color: white; border-radius: .5rem; }
</style>
